<template>
	<conf-module-container :show-page-tools="true">
		<template #Slot-Conf-Module-Header>
			<div class="module-header">
				<p class="boxes-title font-20-bold">盒子管理</p>
				<div>
					<div class="display-change-box">
						<div class="change-item" :class="C_Switch(0)" @click="switchPageTab(0)">
							<global-svg-icon icon-name="card-fill" width="18px" height="18px"></global-svg-icon>
						</div>
						<div class="list-check change-item" :class="C_Switch(1)" @click="switchPageTab(1)">
							<global-svg-icon icon-name="list-check-fill" width="18px" height="18px"></global-svg-icon>
						</div>
					</div>
				</div>
			</div>
		</template>

		<template #Slot-Conf-Module-Tools-Left>
			<div class="left-action-box">
				<div class="flex">
					<global-input-search
						v-model:value="tableAttr.searchObj.select"
						placeholder="盒子名称/SN码"
						class="global-input"
						@search="Search"
					></global-input-search>

					<global-switch-tab :status-data="statusData" @switch-tab="switchStatusTab"></global-switch-tab>
				</div>
				<div class="flex">
					<a-button
						v-if="g6Permission.showBtn('sync_person')"
						type="default"
						style="height: 36px; margin-left: 8px; padding: 7px 16px"
						@click="showSyncPerson = true"
					>
						同步人员数据
					</a-button>

					<a-button
						v-if="g6Permission.showBtn('add-box')"
						type="default"
						style="margin-left: 8px; padding: 7px 16px"
						:loading="manualSynBoxDataLoading"
						@click="manualSynBoxData"
					>
						数据同步
					</a-button>
					<a-button v-if="g6Permission.showBtn('add-box')" type="primary" style="margin-left: 8px; padding: 7px 16px">
						<a-dropdown :trigger="['hover']" @open-change="open">
							<div class="header-user">
								新增盒子
								<global-svg-icon class="svg-icon" :icon-name="iconName" width="16px" height="16px"></global-svg-icon>
							</div>
							<template #overlay>
								<a-menu>
									<a-menu-item key="logout" @click="addBox('now')">
										<a href="javascript:;">新版新增盒子</a>
									</a-menu-item>
									<a-menu-item key="logout" @click="addBox('before')">
										<a href="javascript:;">旧版新增盒子</a>
									</a-menu-item>
								</a-menu>
							</template>
						</a-dropdown>
					</a-button>
				</div>
			</div>
		</template>
		<template #Slot-Conf-Module-Tools-Right> </template>
		<template #Slot-Conf-Module-Content>
			<div class="display-box">
				<!-- ------表格展示------ -->
				<div v-if="tabSignDefault === 1">
					<boxes-table-page
						:table-attr="tableAttr"
						@set-pagination="setTablePagination"
						@page-button-click="buttonClick"
					></boxes-table-page>
				</div>

				<!-- ------卡片展示------ -->
				<vue-scroll v-else-if="tabSignDefault === 0 && cardInfo.length" @handle-scroll="handlePageScroll">
					<a-spin size="large" :spinning="cardInfoLoading" class="loading">
						<div class="card-box">
							<boxes-card-page :card-info="cardInfo" @page-button-click="buttonClick"></boxes-card-page>
						</div>
					</a-spin>
				</vue-scroll>
				<!-- ------结束------ -->
			</div>
			<alarm-configuration v-if="AlarmConfigurationVisible" :serial="serial" @ok="setTableData()" @close="closeModel"></alarm-configuration>
		</template>
	</conf-module-container>

	<sync-person
		v-if="showSyncPerson"
		:box-serial="boxSerial"
		@close="
			() => {
				showSyncPerson = false;
				boxSerial = '';
			}
		"
		@ok="
			() => {
				showSyncPerson = false;
				boxSerial = '';
				tabSignDefault === 1 && setTableData();

				tabSignDefault === 0 && queryCardList();
			}
		"
	></sync-person>
</template>

<script setup lang="ts" name="boxes">
import { g6UseTable } from 'glasssix-vue3-hooks';
import { g6Permission } from 'glasssix-utils-ts';
import { useDeleteModal } from '@/global-hooks/base.hooks';
import { BoxManageApi } from '../../api';
import { TsCardInfo } from '../../type';

import { BoxesCardPage, BoxesTablePage, ConfModuleContainer, AlarmConfiguration, SyncPerson } from '../../components/index';
const $message: any = inject('$message');

const { tableAttr, setTableData, setTablePagination } = g6UseTable(BoxManageApi.list);
const router = useRouter();
const { setOpenDeleteModal } = useDeleteModal();

// 滚动条
const headerBottomBorderColor = ref('transparent');
const iconName = ref<string>('arrow-down-s-line');
const open = (val: any): void => {
	iconName.value = val ? 'icon-wrapper' : 'arrow-down-s-line';
};
const handlePageScroll = (vertical: Record<string, any>): void => {
	headerBottomBorderColor.value = vertical.scrollTop > 10 ? '#20305b' : 'transparent';
};

/** 同步人员数据 */
const showSyncPerson = ref(false);
const boxSerial = ref('');
/**
 * ----------------卡片页操作-----------------
 *  */
const cardInfo = ref<Array<TsCardInfo>>([]);
const cardInfoLoading = ref<boolean>(false);
const AlarmConfigurationVisible = ref<boolean>(false);
const serial = ref('a');

const queryCardList = async (): Promise<void> => {
	cardInfoLoading.value = true;

	const res: TsRes = await BoxManageApi.queryCardList(tableAttr.searchObj);
	cardInfo.value = res.data;
	cardInfo.value.forEach((i: any) => {
		i.visible = false;
	});
	cardInfoLoading.value = false;
};
const statusData = ref<Record<string, string>>({
	allNum: '',
	onlineNum: '',
	offNum: ''
});
// 盒子状态获取
const queryStatusList = async (): Promise<void> => {
	let { data } = await BoxManageApi.queryStatusList();
	statusData.value.allNum = data.total;
	statusData.value.onlineNum = data.online;
	statusData.value.offNum = data.offline;
};
/**
 * ----------------右侧页面显示方式切换-----------------
 *  */
const tabSignDefault = ref<number>(0);
const C_Switch = computed(() => {
	return function name(tabSign: number) {
		return tabSignDefault.value === tabSign ? 'current' : '';
	};
});
// 计算数据展示方式切换
const switchPageTab = (tabSign: number): void => {
	tabSignDefault.value = tabSign;
	tableAttr.data = [];
	cardInfo.value = [];
	switch (tabSign) {
		case 1:
			setTableData();
			break;
		case 0:
			queryCardList();
			break;

		default:
			break;
	}
};
/**
 * ------------------结束-----------------------
 */

/**
 * -----------------------搜索-----------------------
 */
const Search = (): void => {
	if (tabSignDefault.value === 1) {
		setTableData(true);
	} else if (tabSignDefault.value === 0) {
		queryCardList();
	}
};
const switchStatusTab = (status: number | null): void => {
	tableAttr.searchObj.status = status;
	Search();
};

/**
 * ---------------- 操作 -----------------
 *  */
// 删除
const boxDelete = async (record: Record<string, any>): Promise<void> => {
	const deleteFun = async (): Promise<void> => {
		let res: TsRes = await BoxManageApi.delete([record.id]);
		if (res.code === 0) {
			if (tabSignDefault.value === 1) {
				tableAttr.data = tableAttr.data.filter((row: Record<string, any>) => row.id !== record.id);
				tableAttr.total = tableAttr.total - 1;
			}
			if (tabSignDefault.value === 0) {
				queryCardList();
				queryStatusList();
			}
			$message.success('删除成功');
		}
	};
	const deleteModalInfo = { title: '请确认是否删除', okText: '删除', cancelText: '取消' };

	setOpenDeleteModal(deleteFun, deleteModalInfo);
};
// 重启
const reset = (record: Record<string, any>): void => {
	const restartFun = async (): Promise<void> => {
		let res: TsRes = await BoxManageApi.boxRestart(record.serial);
		if (res.code === 0) {
			$message.success('重启成功');
		} else {
			$message.warning(res.message);
		}
	};
	const restartModalInfo = { title: '确定重启', okText: '重启', cancelText: '取消' };
	setOpenDeleteModal(restartFun, restartModalInfo);
};

// 表格操作
const buttonClick = (btnCode: string, record: Record<string, any>): void => {
	console.log('表格操作:', record);

	switch (btnCode) {
		case 'single-delete':
			boxDelete(record);
			break;
		case 'alarm-conf':
			AlarmConfigurationVisible.value = true;
			serial.value = record.serial;
			break;
		case 'reset':
			reset(record);
			break;

		case 'details':
			sessionStorage.setItem('boxManageMode', JSON.stringify(tabSignDefault.value));

			router.replace({
				path: '/config-manage/boxes/boxe-detail',
				query: { id: record.id, boxSerial: record.serial, name: record.boxName, status: record.status }
			});

			// router.replace({
			// 	path: '/config-manage/boxes/detail/basic-info',
			// 	query: { id: record.id, boxSerial: record.serial, name: record.boxName }
			// });
			break;
		case 'refreshData':
			// 表格页时
			queryStatusList();
			if (tabSignDefault.value === 1) {
				setTableData();
			} else if (tabSignDefault.value === 0) {
				// 卡片页时
				queryCardList();
			}
			break;

		case 'single-sync-person':
			boxSerial.value = record.serial;
			showSyncPerson.value = true;
			break;

		default:
			break;
	}
};

onMounted(() => {
	queryStatusList();
	const boxManageMode = JSON.parse(sessionStorage.getItem('boxManageMode') as string);
	if (boxManageMode) {
		tabSignDefault.value = boxManageMode;
	}
	// 表格页时
	if (tabSignDefault.value === 1) {
		setTableData();
	} else if (tabSignDefault.value === 0) {
		// 卡片页时
		queryCardList();
	}
});

// 新增盒子
const addBox = (type: string): void => {
	if (type === 'before') {
		router.push('/config-manage/boxes/add');
	} else {
		router.push('/config-manage/boxes/new-add');
	}
};

const manualSynBoxDataLoading = ref<boolean>(false);
// 数据同步
const manualSynBoxData = async (): Promise<void> => {
	manualSynBoxDataLoading.value = true;
	const res: TsRes = await BoxManageApi.manualSynBoxData();
	if (res.code === 0) {
		$message.success('数据同步成功');
		manualSynBoxDataLoading.value = false;
	}
};
// 刷新页面时缓存页面模式
window.addEventListener('beforeunload', () => {
	sessionStorage.setItem('boxManageMode', JSON.stringify(tabSignDefault.value));
});

// 报警配置
const closeModel = (): void => {
	AlarmConfigurationVisible.value = false;
};
</script>

<style lang="less" scoped>
.module-header {
	display: flex;
	justify-content: space-between;
	width: 100%;

	.boxes-title {
		color: @text01;
	}
	// 右侧页面显示方式切换
	.display-change-box {
		display: flex;

		.list-check {
			margin-right: 8px;
		}

		.change-item {
			display: flex;
			width: 34px;
			height: 34px;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			cursor: pointer;
		}

		.current {
			border-radius: 6px;
			background: @mask04;

			/* 淡阴影/淡XS */
			box-shadow: 0 1px 4px 0 rgba(2, 36, 59, 0.06);
		}
	}
}

.left-action-box {
	display: flex;
	width: 100%;
	justify-content: space-between;

	.flex {
		display: flex;
	}

	.global-input {
		width: 216px;
		margin-right: 8px;
		margin-left: auto;
	}
}

// 数据展示
.display-box {
	padding: 20px 0 0;
	// 卡片展示页
	.card-box {
		display: grid;
		width: 100%;
		grid-template-columns: repeat(auto-fill, minmax(255px, 1fr));
		grid-column-gap: 20px;
		/* stylelint-disable-next-line declaration-block-no-redundant-longhand-properties */
		grid-row-gap: 16px;
	}
}
</style>
